package com.yuexun.dhdoctor.module.commun.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.AppContext;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.CreateGroupAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.DepartOrPeopleData;
import com.yuexun.dhdoctor.module.Contract.bean.GroupGroupData;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/3/28 0028.
 */

public class Act_Choice_Group extends BaseKJActivity {

    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.etSearch2)
    EditText etSearch2;
    @Bind(R.id.btnSearchClear)
    ImageButton btnSearchClear;
    @Bind(R.id.searchLayout)
    LinearLayout searchLayout;
    @Bind(R.id.people_list)
    FixedSwipeListView peopleList;
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.addmember_sure_btn)
    TextView addmemberSureBtn;

    private Context context;
    private Handler handler;
    AddMemberAdapter addMemberAdapter;
    CreateGroupAdapter adapter;
    GroupGroupData groupGroupDataBean;
    ArrayList<People> peoples = new ArrayList<People>();
    ArrayList<People> usersBeans_origin = new ArrayList<People>();

    int from;
    private int isSelectMe;

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_choice_group);
        ButterKnife.bind(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = aty.getApplicationContext();
    }

    @Override
    public void initData() {
        initHandle();

        usersBeans_origin = (ArrayList<People>) getIntent().getExtras().getSerializable("usersBeans");
        groupGroupDataBean = (GroupGroupData) getIntent().getExtras().getSerializable("DataBean");
        isSelectMe = getIntent().getExtras().getInt("isSelectMe", 0);
        from = Integer.valueOf(getIntent().getExtras().getString("from"));

        titleTv.setText(groupGroupDataBean.getTitle());

        for (int i = 0; i < groupGroupDataBean.getToId().size(); i++) {
            People people = new People();
            people.setUserId(groupGroupDataBean.getToId().get(i) + "");
            people.setUserName(groupGroupDataBean.getToName().get(i) + "");
            people.setPinyin(groupGroupDataBean.getPinyin().get(i));
            people.setJobNum(groupGroupDataBean.getJobNum().get(i));
            peoples.add(people);
        }
        addMemberAdapter = new AddMemberAdapter(aty.getApplicationContext(), peoples, usersBeans_origin, handler, isSelectMe, peopleList, from);
        peopleList.setAdapter(addMemberAdapter);

        peopleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isSelectMe == 0) {
                    if (PreferenceHelper.readString(AppContext.getInstance(), AppConfig.USER_INFO, AppConfig.JOB_ID)
                            .equals(peoples.get(position).getJobNum())) {
                        ViewInject.toast("不能选择本人");
                    } else {
                        if (from == 0) {
                            if (usersBeans_origin.contains(peoples.get(position))) {
                                usersBeans_origin.remove(peoples.get(position));
                                addMemberAdapter.notifyDataSetChanged();
                                Message msg = new Message();
                                msg.what = 10003;
                                handler.sendMessage(msg);
                            } else {
                                usersBeans_origin.add(peoples.get(position));
                                addMemberAdapter.notifyDataSetChanged();
                                Message msg = new Message();
                                msg.what = 10003;
                                handler.sendMessage(msg);
                            }
                        } else {
                            if (usersBeans_origin.contains(peoples.get(position))) {
                                usersBeans_origin.remove(peoples.get(position));
                                addMemberAdapter.notifyDataSetChanged();
                                Message msg = new Message();
                                msg.what = 10003;
                                handler.sendMessage(msg);
                            } else {
                                usersBeans_origin.clear();
                                usersBeans_origin.add(peoples.get(position));
                                addMemberAdapter.notifyDataSetChanged();
                                Message msg = new Message();
                                msg.what = 10003;
                                handler.sendMessage(msg);
                            }
                        }
                    }
                } else {
                    if (from == 0) {
                        if (usersBeans_origin.contains(peoples.get(position))) {
                            usersBeans_origin.remove(peoples.get(position));
                            addMemberAdapter.notifyDataSetChanged();
                            Message msg = new Message();
                            msg.what = 10003;
                            handler.sendMessage(msg);
                        } else {
                            usersBeans_origin.add(peoples.get(position));
                            addMemberAdapter.notifyDataSetChanged();
                            Message msg = new Message();
                            msg.what = 10003;
                            handler.sendMessage(msg);
                        }
                    } else {
                        if (usersBeans_origin.contains(peoples.get(position))) {
                            usersBeans_origin.remove(peoples.get(position));
                            addMemberAdapter.notifyDataSetChanged();
                            Message msg = new Message();
                            msg.what = 10003;
                            handler.sendMessage(msg);
                        } else {
                            usersBeans_origin.clear();
                            usersBeans_origin.add(peoples.get(position));
                            addMemberAdapter.notifyDataSetChanged();
                            Message msg = new Message();
                            msg.what = 10003;
                            handler.sendMessage(msg);
                        }
                    }
                }
            }
        });

        etSearch2.addTextChangedListener(new TextWatcher() {
            boolean hasPadding = true;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (TextUtils.isEmpty(s) && !hasPadding) {
                    Message msg = new Message();
                    msg.what = 10002;
                    handler.sendMessage(msg);

                    hasPadding = true;
                } else if (!TextUtils.isEmpty(s) && hasPadding) {
                    Message msg = new Message();
                    msg.what = 10001;
                    handler.sendMessage(msg);

                    hasPadding = false;
                }
                if (addMemberAdapter != null) {
                    addMemberAdapter.getMyFilter(null == s ? "" : s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (etSearch2.getText().toString().length() == 0) {
                    searchLayout.setVisibility(View.VISIBLE);
                } else {
                    searchLayout.setVisibility(View.GONE);
                }
            }
        });

        setGridView();
    }

    void initHandle() {
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 10001: // 搜索有文字的的时候
                        btnSearchClear.setVisibility(View.VISIBLE);
                        break;
                    case 10002: // 搜索没文字的的时候
                        btnSearchClear.setVisibility(View.INVISIBLE);
                        break;
                    case 10003:
                        setGridView();
//                        if (listener != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putSerializable("usersBeans", usersBeans_origin);
//                            listener.showData(bundle);
//                        }
                        break;
                    case 10004:
                        break;
                    case 10005:
                        break;
                    default: // 默认消息处理

                        break;
                }
            }
        };
    }

    @OnClick({R.id.dept_back, R.id.btnSearchClear, R.id.addmember_sure_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dept_back:
                onBackPressed();
                break;
            case R.id.btnSearchClear:
                etSearch2.setText("");
                break;
            case R.id.addmember_sure_btn:
                if (from == 1 && usersBeans_origin.size() > 1) {
                    Toast.makeText(this, "只能选择一个", Toast.LENGTH_SHORT).show();
                } else {
                    if (isSelectMe == 0) {
                        if (!PreferenceHelper.readString(AppContext.getInstance(), AppConfig.USER_INFO, AppConfig.JOB_ID)
                                .equals(usersBeans_origin.get(0).getJobNum())) {
                            Bundle bundle = new Bundle();
                            Intent intent = new Intent();
                            bundle.putSerializable("persons", usersBeans_origin);
                            intent.putExtras(bundle);
                            setResult(10001, intent);
                            finish();
                        } else {
                            ViewInject.toast("不能选择自己为接收对象!");
                        }
                    } else {
                        Bundle bundle = new Bundle();
                        Intent intent = new Intent();
                        bundle.putSerializable("persons", usersBeans_origin);
                        intent.putExtras(bundle);
                        setResult(10001, intent);
                        finish();
                    }
                }
                break;
        }
    }

    private void setGridView() {
        int size = usersBeans_origin.size();

        List<DepartOrPeopleData> datas = new ArrayList<>();
        for (People people : usersBeans_origin) {
            DepartOrPeopleData data = new DepartOrPeopleData();
            data.setDataId(people.getUserId() + "");
            data.setDataName(people.getUserName());
            datas.add(data);
        }

        if (size == 0) {
            addmemberSureBtn.setClickable(false);
            addmemberSureBtn.setBackgroundResource(R.color.line);
            addmemberSureBtn.setText("确认");
        } else {
            addmemberSureBtn.setClickable(true);
            addmemberSureBtn.setBackgroundResource(R.color.app_theme_color);
            addmemberSureBtn.setText("确认(" + size + "人)");
        }

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        adapter = new CreateGroupAdapter(grid, datas, R.layout.item_send_addmember);
        grid.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
        Bundle bundle = new Bundle();
        Intent intent = new Intent();
        bundle.putSerializable("persons", usersBeans_origin);
        intent.putExtras(bundle);
        setResult(0x001, intent);
        finish();
    }
}
